package com.nextbusmn.server.JSONBuilders;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.nextbusmn.server.dataobjects.StopTimeData;

public class StopJSONBuilder {
	
	public static JSONArray getNextTripJSON(List<StopTimeData> stopTimes) {
		
		List<StopTimeData> uniqueTimes = new ArrayList<StopTimeData>();
		
		for (StopTimeData std : stopTimes) {
			boolean uniqueFlag = true;
			for (StopTimeData unique : uniqueTimes) {
				if (std.getDepartureTime().getHours() == unique.getDepartureTime().getHours() &&
						std.getDepartureTime().getMinutes() == unique.getDepartureTime().getMinutes() &&
						std.getTrip().getRouteID() == unique.getTrip().getRouteID()) {
					uniqueFlag = false;;
				}
			}
			if (uniqueFlag) {
				uniqueTimes.add(std);
			}
		}
		
		JSONArray returnArray = new JSONArray();
		try {
			
			for (StopTimeData row : uniqueTimes) {
				JSONObject obj = new JSONObject();
				
				obj.put("t", row.getTripID());  
				obj.put("d", getTimeStringFromDate(row.getDepartureTime()));
				obj.put("h", row.getTrip().getTripHeadsign());
				obj.put("s", row.getTrip().getShapeID());
				obj.put("r", row.getTrip().getRouteID());
				returnArray.put(obj);
			}
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		System.out.println("After duplicates removed : " + uniqueTimes.size());
		return returnArray;
	}

	private static String getTimeStringFromDate(Date departureTime) {
		SimpleDateFormat sdf = new SimpleDateFormat("kkmm");
		sdf.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
		return sdf.format(departureTime);
	}
}
